package com.example.gesture;

import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.content.ContextWrapper;
import android.content.DialogInterface;
import android.gesture.Gesture;
import android.gesture.GestureLibraries;
import android.gesture.GestureLibrary;
import android.gesture.GestureOverlayView;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import java.io.File;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {
    GestureOverlayView gestureOverlayView;
    public Gesture mGesture;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        gestureOverlayView = (GestureOverlayView) findViewById(R.id.gesture);
        gestureOverlayView.setGestureColor(Color.BLUE);
        gestureOverlayView.setGestureStrokeWidth(10);
        gestureOverlayView.addOnGesturePerformedListener(new GestureOverlayView.OnGesturePerformedListener() {
            @Override
            public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) {
                mGesture = gesture;
                View dialog = getLayoutInflater().inflate(R.layout.save_gesture,null);
                ImageView image = (ImageView) dialog.findViewById(R.id.iv_gesture);
                EditText et_gesture_name = (EditText) dialog.findViewById(R.id.et_name);
                Bitmap bitmap = gesture.toBitmap(128,128,10,0xff0000ff);
                image.setImageBitmap(bitmap);
                new AlertDialog.Builder(MainActivity.this).setView(dialog)
                        .setPositiveButton("save", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                //保存
                                String name = et_gesture_name.getText().toString().trim();
                                saveGesture(name);
                            }
                        }).setNegativeButton("Cancel",null).show();
            }
        });
    }
    public void saveGesture(String fileName){
        if(mGesture != null){
            String state = Environment.getExternalStorageState();
            if(state.equals(Environment.MEDIA_MOUNTED)){
                ContextWrapper cw = new ContextWrapper(getApplicationContext());
                File directory = cw.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
                File file = new File(directory,fileName);
                GestureLibrary lib = GestureLibraries.fromFile(file);
                lib.addGesture(fileName,mGesture);
                lib.save();
            }
        }
    }
}